import toast from '@/plugins/toast';

/**
 * 处理 response
 * @param res
 * @param showSuccess
 * @param successMessage
 * @param showError
 * @param errorMessage
 * @returns {Promise<Promise<*|Promise<never>>|*>}
 */
export const handelHttpResponse = async (res, showSuccess = false, successMessage = undefined, showError = true, errorMessage = undefined) => {
    if (res.data.success) {
        if (showSuccess) {
            toast.success(successMessage || res.data.msg || res.data.data || '操作成功');
        }
        return await res.data;
    } else {
        if (showError) {
            toast.error(errorMessage || res.data.msg);
        }
        return Promise.reject(res.data);
    }
};

/**
 * 克隆 Object
 *
 * @param obj
 * @returns {Array}
 */
export const deepClone = (obj) => {
    let result = Array.isArray(obj) ? [] : {};
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (typeof obj[key] === 'object' && obj[key]) {
                result[key] = deepClone(obj[key]);
            } else {
                result[key] = obj[key];
            }
        }
    }
    return result;
};

/**
 * 对比不同的数据，并返回不同的地方
 *
 * @param object
 * @param diffObject
 */
export const objectDiff = (object = [], diffObject = {}) => {
    let newObject = {};

    for (let key in object) {
        if (object[key] !== diffObject[key]) {
            newObject[key] = object[key];
        }
    }

    return newObject;
};

export default {
    handelHttpResponse,
    deepClone,
    objectDiff
}